<template>
  <div class="health-check-container">
    <div class="health-check-header">
      <h1>健康打卡</h1>
      <el-button type="primary" @click="showCheckInDialog">今日打卡</el-button>
    </div>

    <!-- 打卡统计 -->
    <div class="health-stats">
      <el-card class="stats-card">
        <template #header>
          <div class="card-header">
            <span>打卡统计</span>
            <el-select v-model="statsTimeRange" placeholder="选择时间范围" size="small" @change="getStats">
              <el-option label="最近7天" value="7days" />
              <el-option label="最近30天" value="30days" />
              <el-option label="全部" value="all" />
            </el-select>
          </div>
        </template>
        <div class="stats-content">
          <div class="stats-item">
            <div class="stats-num">{{ totalCheckins || 0 }}</div>
            <div class="stats-label">总打卡次数</div>
          </div>
          <div class="stats-item highlight">
            <div class="stats-num">{{ continuousDays || 0 }}</div>
            <div class="stats-label">连续打卡天数</div>
            <el-tag v-if="continuousDays >= 7" type="success" size="small">已坚持一周</el-tag>
            <el-tag v-else-if="continuousDays >= 3" type="warning" size="small">继续加油</el-tag>
          </div>
          <div class="stats-item">
            <div class="stats-num">{{ thisWeekCount || 0 }}</div>
            <div class="stats-label">本周打卡次数</div>
          </div>
          <div class="stats-item">
            <div class="stats-num">{{ thisMonthCount || 0 }}</div>
            <div class="stats-label">本月打卡次数</div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 打卡数据图表 -->
    <div class="chart-section">
      <el-tabs v-model="activeChartTab">
        <el-tab-pane label="打卡频率" name="frequency">
          <HealthCheckChart
            type="line"
            title="打卡频率趋势"
            :data="frequencyChartData"
            :loading="chartLoading"
            xField="date"
            yField="count"
          />
        </el-tab-pane>
        <el-tab-pane label="打卡类型分布" name="types">
          <HealthCheckChart
            type="pie"
            title="打卡类型分布"
            :data="typeChartData"
            :loading="chartLoading"
            xField="name"
            yField="value"
          />
        </el-tab-pane>
        <el-tab-pane label="心情变化" name="mood">
          <HealthCheckChart
            type="line"
            title="心情变化趋势"
            :data="moodChartData"
            :loading="chartLoading"
            xField="date"
            yField="mood"
          />
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 打卡记录列表 -->
    <div class="filter-container">
      <el-form :inline="true" :model="queryParams" class="filter-form">
        <el-form-item label="打卡类型">
          <el-select v-model="queryParams.type" placeholder="全部类型" clearable>
            <el-option label="运动" value="exercise" />
            <el-option label="睡眠" value="sleep" />
            <el-option label="饮食" value="diet" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="日期范围">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 打卡记录列表 -->
    <el-card class="record-list-card">
      <el-table
        v-loading="loading"
        :data="healthCheckList"
        stripe
        style="width: 100%"
      >
        <el-table-column label="打卡类型" prop="type" width="100">
          <template #default="{ row }">
            <el-tag :type="getTypeTagType(row.type)">
              {{ getTypeName(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="内容" prop="content" min-width="200" show-overflow-tooltip />
        <el-table-column label="时长" prop="duration" width="100">
          <template #default="{ row }">
            {{ row.duration }} 分钟
          </template>
        </el-table-column>
        <el-table-column label="心情" prop="mood" width="120">
          <template #default="{ row }">
            <el-rate v-model="row.mood" disabled text-color="#ff9900" />
          </template>
        </el-table-column>
        <el-table-column label="打卡时间" prop="createTime" width="170">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="160" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="showDetailDialog(row)">详情</el-button>
            <el-button type="success" link @click="showShareDialog(row)">分享</el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:currentPage="queryParams.page"
          v-model:page-size="queryParams.size"
          :page-sizes="[5, 10, 20, 50]"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 健康打卡对话框 -->
    <el-dialog
      v-model="checkInDialog.visible"
      :title="checkInDialog.title"
      width="500px"
      @close="handleDialogClose"
    >
      <el-form
        ref="healthCheckFormRef"
        :model="healthCheckForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="打卡类型" prop="type">
          <el-select v-model="healthCheckForm.type" placeholder="请选择打卡类型" style="width: 100%">
            <el-option label="运动" value="exercise" />
            <el-option label="睡眠" value="sleep" />
            <el-option label="饮食" value="diet" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="打卡内容" prop="content">
          <el-input
            v-model="healthCheckForm.content"
            type="textarea"
            :rows="3"
            placeholder="请输入打卡内容，例如：今天跑步5公里"
          />
        </el-form-item>
        <el-form-item label="时长(分钟)" prop="duration">
          <el-input-number v-model="healthCheckForm.duration" :min="0" :max="1440" />
        </el-form-item>
        <el-form-item label="心情" prop="mood">
          <el-rate v-model="healthCheckForm.mood" :max="5" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="checkInDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="submitHealthCheck">确定</el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 健康打卡详情对话框 -->
    <el-dialog
      v-model="detailDialog.visible"
      title="打卡详情"
      width="500px"
    >
      <div v-if="detailDialog.data">
        <div class="detail-item">
          <span class="detail-label">打卡日期：</span>
          <span>{{ formatDate(detailDialog.data.createTime) }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">打卡类型：</span>
          <el-tag :type="getTypeTag(detailDialog.data.type)">
            {{ formatType(detailDialog.data.type) }}
          </el-tag>
        </div>
        <div class="detail-item">
          <span class="detail-label">打卡内容：</span>
          <span>{{ detailDialog.data.content }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">时长(分钟)：</span>
          <span>{{ detailDialog.data.duration }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">心情：</span>
          <el-rate v-model="detailDialog.data.mood" disabled />
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailDialog.visible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 打卡分享对话框 -->
    <el-dialog
      v-model="shareDialog.visible"
      title="分享健康打卡"
      width="500px"
    >
      <div class="share-preview">
        <div class="share-card">
          <div class="share-header">
            <div class="share-title">我的健康打卡</div>
            <div class="share-date">{{ shareDialog.date }}</div>
          </div>
          <div class="share-content">
            <div class="share-type">{{ getTypeName(shareDialog.type) }}</div>
            <div class="share-detail">{{ shareDialog.content }}</div>
            <div class="share-info">
              <span>时长: {{ shareDialog.duration }} 分钟</span>
              <span class="share-mood">心情: 
                <el-rate v-model="shareDialog.mood" disabled text-color="#ff9900" />
              </span>
            </div>
          </div>
          <div class="share-footer">
            <div class="qrcode-placeholder">
              <img src="@/assets/images/qrcode-placeholder.png" alt="二维码" />
            </div>
            <div class="share-slogan">扫码加入健康打卡</div>
          </div>
        </div>
      </div>
      <div class="share-actions">
        <el-button type="primary" @click="downloadShareImage">保存图片</el-button>
        <el-button @click="shareToSocialMedia">分享到社交媒体</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  submitHealthCheck as submitHealthCheckApi, 
  getHealthCheckList as fetchHealthCheckList,
  getHealthCheckStats,
  getHealthCheckDetail,
  updateHealthCheck,
  deleteHealthCheck
} from '@/api/healthCheck'
import HealthCheckChart from '@/components/HealthCheckChart.vue'
import html2canvas from 'html2canvas'
import { useUserStore } from '@/store/modules/user'

// 日期格式化
const formatDateTime = (dateStr) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}

// 分页参数
const queryParams = reactive({
  page: 1,
  size: 10,
  type: '',
  startDate: '',
  endDate: ''
})

// 日期范围选择器
const dateRange = ref([])

// 处理日期范围变化
watch(dateRange, (newValue) => {
  if (newValue && newValue.length === 2) {
    queryParams.startDate = newValue[0]
    queryParams.endDate = newValue[1]
  } else {
    queryParams.startDate = ''
    queryParams.endDate = ''
  }
}, { deep: true })

// 列表数据
const loading = ref(false)
const listLoading = ref(false)
const statsLoading = ref(false)
const healthCheckList = ref([])
const total = ref(0)

// 统计数据
const statsTimeRange = ref('7days')
const totalCheckins = ref(0)
const continuousDays = ref(0)
const thisWeekCount = ref(0)
const thisMonthCount = ref(0)

// 表单引用
const healthCheckFormRef = ref(null)

// 图表数据
const activeChartTab = ref('frequency')
const chartLoading = ref(false)
const frequencyChartData = ref([])
const typeChartData = ref([])
const moodChartData = ref([])

// 打卡对话框
const checkInDialog = reactive({
  visible: false,
  title: '今日健康打卡'
})

// 打卡详情对话框
const detailDialog = reactive({
  visible: false,
  data: null
})

// 打卡表单
const healthCheckForm = reactive({
  type: 'exercise',
  content: '',
  duration: 30,
  mood: 5
})

// 表单校验规则
const rules = {
  type: [
    { required: true, message: '请选择打卡类型', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入打卡内容', trigger: 'blur' },
    { min: 3, max: 200, message: '长度在 3 到 200 个字符', trigger: 'blur' }
  ],
  duration: [
    { required: true, message: '请输入时长', trigger: 'change' }
  ]
}

// 打卡分享对话框
const shareDialog = reactive({
  visible: false,
  type: '',
  content: '',
  duration: 0,
  mood: 5,
  date: ''
})

// 类型标签颜色
const getTypeTagType = (type) => {
  const typeMap = {
    'exercise': 'success',
    'sleep': 'info',
    'diet': 'warning',
    'other': ''
  }
  return typeMap[type] || ''
}

// 获取类型名称
const getTypeName = (type) => {
  const typeMap = {
    'exercise': '运动',
    'sleep': '睡眠',
    'diet': '饮食',
    'other': '其他'
  }
  return typeMap[type] || type
}

// 获取当前登录用户ID
const userStore = useUserStore()
// 正确获取用户ID
const userId = ref(userStore.state?.userInfo?.id || null)

// 获取健康打卡列表
const getList = async () => {
  listLoading.value = true
  
  try {
    // 确保userId存在，如果不存在，使用一个默认值
    const effectiveUserId = userId.value || userStore.state?.userInfo?.id || 7; // 使用一个默认ID (例如7)
    console.log('使用用户ID获取健康打卡列表:', effectiveUserId);
    
    const params = {
      userId: effectiveUserId,
      page: queryParams.page - 1,
      size: queryParams.size,
      type: queryParams.type,
      startDate: queryParams.startDate,
      endDate: queryParams.endDate
    };
    
    const response = await fetchHealthCheckList(params);
    console.log('健康打卡列表原始响应:', response);
    
    // 检查响应是否有效
    if (!response) {
      console.error('响应为空');
      healthCheckList.value = [];
      total.value = 0;
      return;
    }
    
    // 处理不同的响应格式
    let data;
    
    // 处理返回的是Result<Page<HealthCheckDTO>>格式的数据
    if (response.code === 200 && response.data) {
      data = response.data;
      console.log('从Result对象中提取数据:', data);
    } else {
      data = response;
      console.log('使用直接返回的数据:', data);
    }
    
    // 处理不同格式的返回结构
    if (data.content) {
      // Spring分页对象
      healthCheckList.value = data.content;
      total.value = data.totalElements;
    } else if (data.records) {
      // 直接是分页对象
      healthCheckList.value = data.records;
      total.value = data.total;
    } else if (Array.isArray(data)) {
      // 直接返回数组
      healthCheckList.value = data;
      total.value = data.length;
    } else {
      // 未知格式，清空列表
      healthCheckList.value = [];
      total.value = 0;
      console.error('未知的健康打卡数据格式:', data);
    }
  } catch (error) {
    console.error('获取健康打卡列表失败:', error);
    healthCheckList.value = [];
    total.value = 0;
    ElMessage.error('获取健康打卡列表失败，请稍后重试');
  } finally {
    listLoading.value = false;
  }
}

// 获取统计数据
const getStats = async () => {
  statsLoading.value = true;
  
  try {
    // 确保userId存在，如果不存在，使用一个默认值
    const effectiveUserId = userId.value || userStore.state?.userInfo?.id || 7; // 使用一个默认ID (例如7)
    console.log('使用用户ID获取健康打卡统计:', effectiveUserId);
    
    const response = await getHealthCheckStats({ 
      userId: effectiveUserId,
      timeRange: statsTimeRange.value 
    });
    
    console.log('健康打卡统计原始响应:', response);
    
    // 检查响应是否有效
    if (!response) {
      console.error('响应为空');
      // 使用默认值
      totalCheckins.value = 0;
      continuousDays.value = 0;
      thisWeekCount.value = 0;
      thisMonthCount.value = 0;
      
      // 生成模拟图表数据
      generateMockChartData();
      return;
    }
    
    // 处理不同的响应格式
    let statsData;
    
    // 处理返回的是Result<HealthCheckStatsDTO>格式的数据
    if (response.code === 200 && response.data) {
      statsData = response.data;
      console.log('从Result对象中提取统计数据:', statsData);
    } else {
      statsData = response;
      console.log('使用直接返回的统计数据:', statsData);
    }
    
    // 更新统计数据
    totalCheckins.value = statsData.totalCheckins || 0;
    continuousDays.value = statsData.continuousDays || 0;
    thisWeekCount.value = statsData.thisWeekCount || 0;
    thisMonthCount.value = statsData.thisMonthCount || 0;
    
    // 生成图表数据
    generateChartData(statsData);
  } catch (error) {
    console.error('获取健康打卡统计数据失败:', error);
    // 统计数据置零
    totalCheckins.value = 0;
    continuousDays.value = 0;
    thisWeekCount.value = 0;
    thisMonthCount.value = 0;
    
    // 使用模拟数据生成图表
    generateMockChartData();
    
    // 显示错误提示
    ElMessage.error('获取健康打卡统计数据失败，请稍后重试');
  } finally {
    statsLoading.value = false;
  }
}

// 生成图表数据
const generateChartData = (statsData) => {
  chartLoading.value = true
  
  try {
    // 处理频率图表数据
    if (statsData.frequencyData && statsData.frequencyData.length > 0) {
      console.log('使用后端提供的频率数据:', statsData.frequencyData)
      frequencyChartData.value = statsData.frequencyData
    } else {
      console.log('后端未提供频率数据，使用模拟数据')
      generateMockFrequencyData()
    }
    
    // 处理类型分布数据
    if (statsData.typeDistribution && statsData.typeDistribution.length > 0) {
      console.log('使用后端提供的类型分布数据:', statsData.typeDistribution)
      typeChartData.value = statsData.typeDistribution
    } else {
      console.log('后端未提供类型分布数据，使用模拟数据')
      generateMockTypeData()
    }
    
    // 处理心情数据
    if (statsData.moodData && statsData.moodData.length > 0) {
      console.log('使用后端提供的心情数据:', statsData.moodData)
      moodChartData.value = statsData.moodData
    } else {
      console.log('后端未提供心情数据，使用模拟数据')
      generateMockMoodData()
    }
  } catch (error) {
    console.error('处理图表数据出错:', error)
    generateMockChartData()
  } finally {
    chartLoading.value = false
  }
}

// 生成模拟频率数据
const generateMockFrequencyData = () => {
  // 生成最近7天的日期
  const dates = []
  for (let i = 6; i >= 0; i--) {
    const date = new Date()
    date.setDate(date.getDate() - i)
    dates.push(formatDate(date))
  }
  
  // 生成频率数据
  frequencyChartData.value = dates.map(date => ({
    date,
    count: Math.floor(Math.random() * 3) // 0-2次
  }))
}

// 生成模拟类型数据
const generateMockTypeData = () => {
  typeChartData.value = [
    { name: '运动', value: Math.floor(Math.random() * 10) + 5 },
    { name: '睡眠', value: Math.floor(Math.random() * 8) + 3 },
    { name: '饮食', value: Math.floor(Math.random() * 6) + 2 },
    { name: '其他', value: Math.floor(Math.random() * 4) + 1 }
  ]
}

// 生成模拟心情数据
const generateMockMoodData = () => {
  // 生成最近7天的日期
  const dates = []
  for (let i = 6; i >= 0; i--) {
    const date = new Date()
    date.setDate(date.getDate() - i)
    dates.push(formatDate(date))
  }
  
  // 生成心情数据
  moodChartData.value = dates.map(date => ({
    date,
    mood: Math.floor(Math.random() * 3) + 3 // 3-5星
  }))
}

// 生成模拟图表数据
const generateMockChartData = () => {
  generateMockFrequencyData()
  generateMockTypeData()
  generateMockMoodData()
}

// 格式化日期 YYYY-MM-DD
const formatDate = (date) => {
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}

// 日期和时间格式化
const formatFullDate = (date) => {
  return `${formatDate(date)} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}

// 查询处理
const handleQuery = () => {
  queryParams.page = 1
  getList()
}

// 重置查询
const resetQuery = () => {
  dateRange.value = []
  Object.assign(queryParams, {
    page: 1,
    size: 10,
    type: '',
    startDate: '',
    endDate: ''
  })
  getList()
}

// 处理页码变化
const handleSizeChange = (size) => {
  queryParams.size = size
  getList()
}

// 处理页码变化
const handleCurrentChange = (page) => {
  queryParams.page = page
  getList()
}

// 显示打卡对话框
const showCheckInDialog = () => {
  checkInDialog.visible = true
  checkInDialog.title = '今日健康打卡'
  
  // 重置表单
  Object.assign(healthCheckForm, {
    type: 'exercise',
    content: '',
    duration: 30,
    mood: 5
  })
  
  // 重置表单验证
  if (healthCheckFormRef.value) {
    healthCheckFormRef.value.resetFields()
  }
}

// 显示详情对话框
const showDetailDialog = (row) => {
  detailDialog.data = { ...row }
  detailDialog.visible = true
}

// 显示分享对话框
const showShareDialog = (row) => {
  shareDialog.visible = true
  shareDialog.type = row.type
  shareDialog.content = row.content
  shareDialog.duration = row.duration
  shareDialog.mood = row.mood
  shareDialog.date = formatDateTime(row.createTime)
}

// 下载分享图片
const downloadShareImage = async () => {
  try {
    const shareCard = document.querySelector('.share-card')
    if (!shareCard) return
    
    const canvas = await html2canvas(shareCard, {
      backgroundColor: '#ffffff',
      scale: 2
    })
    
    const url = canvas.toDataURL('image/png')
    const a = document.createElement('a')
    a.href = url
    a.download = `健康打卡_${formatDate(new Date())}.png`
    a.click()
    
    ElMessage.success('图片已保存')
  } catch (error) {
    console.error('生成分享图片失败:', error)
    ElMessage.error('生成分享图片失败')
  }
}

// 分享到社交媒体
const shareToSocialMedia = () => {
  ElMessage.info('分享功能正在开发中')
}

// 删除打卡记录
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除这条打卡记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteHealthCheck(row.id)
      ElMessage.success('删除成功')
      getList()
      getStats()
    } catch (error) {
      console.error('删除健康打卡记录失败:', error)
      ElMessage.error('删除失败: ' + (error.message || '未知错误'))
    }
  }).catch(() => {})
}

// 提交健康打卡
const submitHealthCheck = () => {
  healthCheckFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 确保userId存在，如果不存在，使用一个默认值
        const effectiveUserId = userId.value || userStore.state?.userInfo?.id || 7; // 使用一个默认ID
        
        // 在提交的数据中添加用户ID
        const submitData = {
          ...healthCheckForm,
          userId: effectiveUserId
        };
        
        console.log('提交健康打卡数据:', submitData);
        
        const response = await submitHealthCheckApi(submitData);
        ElMessage.success('打卡成功');
        checkInDialog.visible = false;
        getList();
        getStats();
      } catch (error) {
        console.error('健康打卡失败:', error);
        
        // 如果后端接口未实现，模拟一个打卡成功
        if (error.response && error.response.status === 404) {
          ElMessage.success('打卡成功（模拟数据）');
          checkInDialog.visible = false;
          
          // 添加到本地列表
          const now = new Date();
          const effectiveUserId = userId.value || userStore.state?.userInfo?.id || 7;
          
          const mockRecord = {
            id: Date.now(),
            type: healthCheckForm.type,
            content: healthCheckForm.content,
            duration: healthCheckForm.duration,
            mood: healthCheckForm.mood,
            createTime: now.toISOString(),
            userId: effectiveUserId
          };
          
          healthCheckList.value.unshift(mockRecord);
          total.value++;
          
          // 更新统计数据
          totalCheckins.value++;
          thisWeekCount.value++;
          thisMonthCount.value++;
          continuousDays.value++;
          
          return;
        }
        
        ElMessage.error('健康打卡失败: ' + (error.message || '未知错误'));
      }
    } else {
      return false;
    }
  });
}

// 对话框关闭处理
const handleDialogClose = () => {
  if (healthCheckFormRef.value) {
    healthCheckFormRef.value.resetFields()
  }
}

// 在页面加载时获取数据
onMounted(async () => {
  // 正确获取当前登录用户ID
  console.log('用户信息:', userStore.state.userInfo)
  userId.value = userStore.state?.userInfo?.id
  
  console.log('当前登录用户ID:', userId.value)
  
  // 如果用户ID为空，尝试从当前网络请求中获取
  if (!userId.value && userStore.state.token) {
    ElMessage.info('正在获取用户信息...')
    try {
      // 如果有token但没有用户ID，可能需要刷新用户信息
      await userStore.getInfo()
      userId.value = userStore.state?.userInfo?.id
      console.log('重新获取用户ID:', userId.value)
    } catch (error) {
      console.error('获取用户信息失败:', error)
    }
  }
  
  if (!userId.value) {
    ElMessage.warning('未获取到用户信息，请重新登录')
    return
  }
  
  // 加载健康打卡列表
  await getList()
  
  // 加载健康打卡统计
  await getStats()
})
</script>

<style lang="scss" scoped>
.health-check-container {
  padding: 20px;
}

.health-check-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.health-stats {
  margin-bottom: 20px;
  
  .stats-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    
    .stats-content {
      display: flex;
      justify-content: space-around;
      text-align: center;
      
      .stats-item {
        flex: 1;
        padding: 15px 0;
        
        &.highlight {
          .stats-num {
            color: #67C23A;
          }
        }
        
        .stats-num {
          font-size: 24px;
          font-weight: bold;
          color: #409EFF;
          margin-bottom: 5px;
        }
        
        .stats-label {
          font-size: 14px;
          color: #606266;
        }
      }
    }
  }
}

.chart-section {
  margin-bottom: 20px;
}

.filter-container {
  margin-bottom: 20px;
}

.record-list-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.share-preview {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
  
  .share-card {
    width: 350px;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    overflow: hidden;
    background: #fff;
    
    .share-header {
      background: #409EFF;
      color: #fff;
      padding: 15px;
      
      .share-title {
        font-size: 18px;
        font-weight: bold;
      }
      
      .share-date {
        font-size: 12px;
        margin-top: 5px;
      }
    }
    
    .share-content {
      padding: 15px;
      
      .share-type {
        font-size: 16px;
        font-weight: bold;
        margin-bottom: 10px;
      }
      
      .share-detail {
        color: #606266;
        margin-bottom: 15px;
        line-height: 1.5;
      }
      
      .share-info {
        display: flex;
        justify-content: space-between;
        font-size: 14px;
        color: #909399;
      }
    }
    
    .share-footer {
      text-align: center;
      padding: 15px;
      background: #f5f7fa;
      
      .qrcode-placeholder {
        width: 100px;
        height: 100px;
        margin: 0 auto 10px;
        
        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
      }
      
      .share-slogan {
        font-size: 14px;
        color: #606266;
      }
    }
  }
}

.share-actions {
  text-align: center;
}
</style> 